<!-- eslint-disable ts/no-use-before-define -->
<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue'
import ClassLessonPicker from '../class/ClassLessonPicker.vue'
import ClassStatus from '../class/components/ClassStatus.vue'
import CancelTypeSelect from './CancelTypeSelect.vue'
import EnrollClassSelectPanel from '@/views/education/enroll/components/EnrollClassSelectPanel.vue'
import { ClassChangeApi, EnrollmentApi, StudentApi } from '@/apis'
import getAvatar from '@/utils/avatar'
import { formatMoney } from '@/utils/common'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import ProTable from '@/components/ProTable/index.vue'
import { useForm } from '@/hooks'

defineOptions({
  name: 'ClassCancelCreate',
})

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const { form, resetForm } = useForm<ClassChangeApi.ClassCancelReq>({
  orderItemId: '',
  classId: '',
  studentId: '',
  onlyRemainLesson: false,
  changeType: 'CANCEL_CLASS',
  refundType: 'OFFLINE',
  cancelLessonIndexList: undefined,
})
const enrollLessonList = ref<Array<EnrollmentApi.EnrollLessonResp & { selected: boolean }>>([])

const enrollLessonGroupByOrder = ref<Record<string, Array<EnrollmentApi.EnrollLessonResp & { selected: boolean }>>>({})
const cancelOrderItemId = ref()
const cancelLessonList = computed(() => {
  if (cancelOrderItemId.value && enrollLessonGroupByOrder.value[cancelOrderItemId.value]) {
    return enrollLessonGroupByOrder.value[cancelOrderItemId.value].filter(item => item.selected)
  } else {
    return []
  }
})
const cancelLessonIndexList = computed(() => {
  return cancelLessonList.value.map(item => item.lessonIndex)
})

const refundPrice = computed(() => {
  return cancelLessonList.value.reduce((sum, item) => sum + item.lessonStudent.lessonPrice, 0)
})
// 学生信息
const studentInfo = ref<StudentApi.StudentDetailResp>()
const onStudentSelect = async (studentId) => {
  if (!studentId) {
    return
  }
  resetData()
  studentInfo.value = await StudentApi.getStudentDetail(studentId)
  form.studentId = studentId
}

// 转出班级信息
const expandable = {}
const originalClassTableRef = ref<InstanceType<typeof ProTable>>()
const originalClassColumns: TableInstanceColumns[] = [
  { title: '班级', slotName: 'name', fixed: 'left', width: 360 },
  { title: '年份科目', dataIndex: 'classYear', slotName: 'classYear', width: 150 },
  { title: '校区教室', dataIndex: 'campusId', slotName: 'classroom', width: 120 },
  { title: '班级状态', dataIndex: 'classStatus', slotName: 'classStatus', width: 120 },
  { title: '上课进度(上/退/总)', dataIndex: 'classProgress', slotName: 'classProgress', width: 160 },
  { title: '退课课次', dataIndex: 'changeInfo', slotName: 'changeInfo', width: 160 },
]

const originalClassList = ref<EnrollmentApi.EnrollClassResp[]>([])
const originalClassSelectPanelRef = ref<InstanceType<typeof EnrollClassSelectPanel>>()
const openEnrollClassSelect = () => {
  if (!studentInfo.value?.id) {
    return Message.warning('请选择学生')
  }
  originalClassSelectPanelRef.value?.open(studentInfo.value.id)
}

const onOriginalClassSelect = async (key, record) => {
  if (originalClassList.value.find(item => item.id === key)) {
    return Message.warning('已选择该班级')
  }
  originalClassList.value = [{ ...record }]
  form.classId = key

  // 查询学生课次
  const query = {
    studentId: studentInfo.value!.id,
    enrollmentId: originalClassList.value[0].enrollment.id,
  }
  const res = await EnrollmentApi.getEnrollLessonList(query)
  enrollLessonList.value = res.map(item => ({
    ...item,
    selected: !item.lessonStudent.signInStatus,
  }))
  const group = {}
  enrollLessonList.value.forEach((item) => {
    if (!group[item.lessonStudent.orderItemId]) {
      group[item.lessonStudent.orderItemId] = []
      // group[item.lessonStudent.orderItemId + 1] = []
    }
    group[item.lessonStudent.orderItemId].push(item)
    // group[item.lessonStudent.orderItemId + 1].push(item)
  })
  enrollLessonGroupByOrder.value = group
  const keys = Object.keys(enrollLessonGroupByOrder.value)
  cancelOrderItemId.value = keys.length > 0 ? keys[0] : undefined
  originalClassTableRef.value?.tableRef?.expandAll()
}

const getEnrollClass = async (enrollmentId) => {
  const res = await EnrollmentApi.getEnrollClass(enrollmentId)
  onOriginalClassSelect(res.id, res)
}

const onSave = async () => {
  try {
    form.orderItemId = cancelOrderItemId.value
    form.cancelLessonIndexList = cancelLessonIndexList.value
    await ClassChangeApi.createCancelRecord(form)
    Modal.success({
      title: '操作成功',
      content: '发起退班退课申请成功，等待财务人员审核',
      okText: '查看记录',
      escToClose: false,
      onOk: () => {
        resetData()
        router.push({ path: '/education/class/cancel/list' })
      },
    })
  } catch (err) {
    console.warn('退班退课失败: ', err)
  }
}

const resetData = async () => {
  resetForm()
  studentInfo.value = undefined
  originalClassList.value = []
}

watchEffect(async () => {
  // if (form.studentId && cancelLessonIndexList.value.length > 0) {
  //   const data = {
  //     studentId: studentInfo.value?.id,
  //     couponIdList: selectedCouponIds.value,
  //     orderItemList: orderClassList.value.map(item => ({
  //       classId: item.id,
  //       lessonIndexes: item.lessonList.filter(lesson => lesson.selected).map(lesson => lesson.lessonIndex),
  //     })),
  //   }
  //   orderPriceDetail.value = await OrderApi.calculatePrice(data)
  // }
})

watchEffect(async () => {
  if (route.query.studentId) {
    await onStudentSelect(route.query.studentId as string)
  }
  if (route.query.type) {
    form.changeType = route.query.type
  }
  if (route.query.enrollmentId) {
    getEnrollClass(route.query.enrollmentId)
  }
})
</script>

<template>
  <ProPage>
    <template #title>
      <a-page-header title="发起退班退课" subtitle="" @back="router.back()" />
    </template>
    <CancelTypeSelect v-model="form.changeType" />
    <a-card title="学生" class="section">
      <template #extra>
        <StudentSelect class="min-w-260px" @select="onStudentSelect" />
      </template>
      <div class="flex gap-4">
        <a-image width="54" :src="getAvatar(studentInfo?.avatar, studentInfo?.gender)" />
        <div v-if="studentInfo">
          <div class="mb-3">
            <span class="font-size-16px font-600">{{ studentInfo.name }}</span>
            <icon-woman v-if="studentInfo.gender === 2" :size="16" :style="{ color: '#FF0088' }" />
            <icon-man v-else :size="16" :style="{ color: '#165DFF' }" />
          </div>
          <CellDict :value="studentInfo.enrollStatus" code="EnrollStatusEnum" />
        </div>
        <div class="ml-6 flex-1">
          <a-row>
            <a-col :span="8">
              <span class="label">联系方式</span>
              <span class="value">{{ studentInfo?.parentPhone }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">出生年月</span>
              <span class="value">{{ studentInfo?.birthdate?.substring(0, 7) || '-' }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">入学年份</span>
              <span class="value">{{ studentInfo?.admissionYear ? `${studentInfo.admissionYear}年` : '-' }}</span>
            </a-col>
          </a-row>
          <a-row class="mt-4">
            <a-col :span="8">
              <span class="label">就读学校</span>
              <span class="value">{{ studentInfo?.fulltimeSchool || '-' }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">加入时间</span>
              <span class="value">{{ studentInfo?.createTime || '-' }}</span>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-divider />
    <a-card title="班级" class="section">
      <template #extra>
        <a-button type="primary" @click="openEnrollClassSelect">
          <template #icon>
            <icon-plus />
          </template>
          <span>选择班级</span>
        </a-button>
      </template>
      <ProTable ref="originalClassTableRef" :data="originalClassList" :columns="originalClassColumns" :loading="loading" :pagination="false" :expandable="expandable" default-expand-all-rows>
        <!-- <template #title-panel>
          <a-checkbox v-model="form.onlyRemainLesson" :default-checked="true">
            仅转所有剩余未上课次
          </a-checkbox>
        </template> -->
        <template #expand-row="{ record }">
          <a-radio-group v-model="cancelOrderItemId">
            <template v-for="(items, key, index) in enrollLessonGroupByOrder" :key="key">
              <a-radio :value="key">
                <template #radio="{ checked }">
                  <div
                    class="custom-radio-card"
                    :class="{ 'custom-radio-card-checked': checked }"
                  >
                    <div class="custom-radio-card-title">
                      <div class="custom-radio-card-mask">
                        <span class="custom-radio-card-mask-dot" />
                      </div>
                      <span class="text-gray-9">
                        订单项{{ index + 1 }}
                      </span>
                      <span class="ml text-13px text-gray">
                        {{ key }}
                      </span>
                    </div>
                    <a-divider />
                    <ClassLessonPicker :lesson-list="items" />
                  </div>
                </template>
              </a-radio>
            </template>
          </a-radio-group>
        </template>
        <template #name="{ record }">
          <CellClassInfo :id="record.id" :name="record.name" :lead-teacher-name="record.leadTeacherName" :assist-teacher-name="record.assistTeacherName" />
        </template>
        <template #classYear="{ record }">
          <DictLabel v-model="record.grade" code="Grade" /> · <DictLabel v-model="record.subject" code="Subject" />
          <div class="text-13px text-gray-4">
            {{ record.classYear }}年 · <DictLabel v-model="record.term" code="TermEnum" />
          </div>
        </template>
        <template #classroom="{ record }">
          <div>{{ record.classroomName || '-' }}</div>
          <div class="text-13px text-gray-4">
            {{ record.campusName }}
          </div>
        </template>
        <template #classStatus="{ record }">
          <ClassStatus code="ClassStatusEnum" :status="record.classStatus" />
        </template>
        <template #classProgress="{ record }">
          {{ record.enrollment.completedLessonCount }}/{{ record.enrollment.cancelLessonCount }}/{{ record.enrollment.enrollLessonCount }}
        </template>
        <template #changeInfo="{ record }">
          <a-trigger position="top" auto-fit-position>
            <a-typography-text type="primary" class="cursor-pointer">
              退{{ cancelLessonIndexList.length }}次课
            </a-typography-text>
            <template #content>
              <div class="tooltip-content">
                第{{ cancelLessonIndexList.join('、') }}节课
              </div>
            </template>
          </a-trigger>
        </template>
      </ProTable>
    </a-card>
    <a-divider />
    <a-card title="退费信息" class="section">
      <div class="order-info flex-row-end-center">
        <a-space direction="vertical">
          <div class="h-22px flex-row-end-center text-align-right">
            <span class="w-100px">退费课次:</span>
            <span class="w-140px color-[#4E5969]">
              <a-trigger position="top" auto-fit-position>
                <a-typography-text type="primary" class="cursor-pointer">
                  {{ cancelLessonIndexList.length }}节
                </a-typography-text>
                <template #content>
                  <div class="tooltip-content">
                    第{{ cancelLessonIndexList.join('、') }}节课
                  </div>
                </template>
              </a-trigger></span>
          </div>
          <div class="h-22px flex-row-end-center text-align-right">
            <span class="w-100px">退费金额:</span>
            <span class="w-140px text-align-right font-size-20px color-[#F53F3F] font-600">{{ formatMoney(refundPrice) }}</span>
          </div>
          <div class="h-22px flex-row-end-center text-align-right">
            <span class="w-100px">退费方式:</span>
            <span class="w-140px color-[#4E5969]">
              <DictSelect v-model="form.refundType" code="PayTypeEnum" type="button" />
            </span>
          </div>
        </a-space>
      </div>
    </a-card>
    <div class="submit mt-4 flex justify-end bg-white py-3">
      <a-button type="primary" :loading="loading" @click="onSave">
        <template #icon>
          <icon-check />
        </template>
        <span>提交</span>
      </a-button>
    </div>
    <EnrollClassSelectPanel ref="originalClassSelectPanelRef" @select="onOriginalClassSelect" />
  </ProPage>
</template>

<style lang='less' scoped>
:deep(.arco-page-header-wrapper) {
  padding-left: 0;
}
:deep(.arco-form-item-label-col) {
  padding-right: 10px;
  width: 50px;
}

:deep(.pro-table-toolbar) {
  display: none;
}
.arco-divider {
  margin: 10px 0;
}
.label {
  display: inline-block;
  width: 80px;
  color: #888;
  flex-shrink: 0;
}
.value {
  color: #111;
}
.class-info {
  display: grid;
  grid-template-rows: repeat(4, 1fr);
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
.lesson {
  :deep(.arco-card-body) {
    padding-top: 0 !important;
    background: #fff;
  }
}
:deep(.arco-card-body) {
  padding-top: 0 !important;
  background: #fff;
}

.active {
  border: 1px solid #fe840e;
  background: rgba(255, 125, 0, 0.1);
}

.tooltip-content {
  padding: 10px;
  background-color: var(--color-bg-popup);
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
}

.order-info {
  padding: 20px;
  border-radius: 10px;
  background: #f5f7fd;

  .item-label {
    width: 100px;
    // color: var(--text-3, #86909c);
  }
  // .item-value {
  //   width: 240px;
  //   // color: var(--text-3, #86909c);
  // }
}

// 订单选择自定义
.custom-radio-card {
  padding: 10px 16px;
  background: white;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  box-sizing: border-box;
  margin-bottom: 20px;
}

.custom-radio-card-mask {
  height: 14px;
  width: 14px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 100%;
  border: 1px solid var(--color-border-2);
  box-sizing: border-box;
}

.custom-radio-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
}

.custom-radio-card-mask-dot {
  width: 8px;
  height: 8px;
  border-radius: 100%;
}

custom-radio-card:hover,
.custom-radio-card-checked,
.custom-radio-card:hover .custom-radio-card-mask,
.custom-radio-card-checked .custom-radio-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-radio-card-checked {
  // background-color: var(--color-primary-light-1);
}

.custom-radio-card:hover .custom-radio-card-title,
.custom-radio-card-checked .custom-radio-card-title {
  color: rgb(var(--primary-6));
}

.custom-radio-card-checked .custom-radio-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
